import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class RecreateActivityParticipantsTable1625000000005 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 检查表是否存在
    const tableExists = await queryRunner.hasTable('activity_participants');
    
    // 如果表存在，我们需要备份数据，然后重新创建表
    if (tableExists) {
      console.log('activity_participants 表存在，准备重建表');
      
      // 创建临时表
      await queryRunner.query(`
        CREATE TABLE activity_participants_temp (
          id INT AUTO_INCREMENT PRIMARY KEY,
          userId INT NOT NULL,
          activityId INT NOT NULL,
          hasCheckedIn BOOLEAN DEFAULT false,
          checkinTime DATETIME NULL,
          joinTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      
      // 检查原表中的列
      const hasUserIdOld = await queryRunner.hasColumn('activity_participants', 'user_id');
      const hasUserId = await queryRunner.hasColumn('activity_participants', 'userId');
      const hasActivityIdOld = await queryRunner.hasColumn('activity_participants', 'activity_id');
      const hasActivityId = await queryRunner.hasColumn('activity_participants', 'activityId');
      
      // 构建复制数据的SQL
      let userIdColumn = hasUserId ? 'userId' : (hasUserIdOld ? 'user_id' : null);
      let activityIdColumn = hasActivityId ? 'activityId' : (hasActivityIdOld ? 'activity_id' : null);
      
      if (userIdColumn && activityIdColumn) {
        // 复制数据到临时表
        try {
          await queryRunner.query(`
            INSERT INTO activity_participants_temp (id, userId, activityId, hasCheckedIn, checkinTime, joinTime, updatedAt)
            SELECT 
              id, 
              ${userIdColumn} as userId, 
              ${activityIdColumn} as activityId,
              hasCheckedIn,
              checkinTime,
              joinTime,
              updatedAt
            FROM activity_participants
            WHERE ${userIdColumn} IS NOT NULL AND ${activityIdColumn} IS NOT NULL
          `);
          console.log('数据已复制到临时表');
        } catch (error) {
          console.log('复制数据时出错，可能是列不匹配:', error.message);
          // 尝试只复制ID和关键列
          try {
            await queryRunner.query(`
              INSERT INTO activity_participants_temp (id, userId, activityId)
              SELECT 
                id, 
                ${userIdColumn} as userId, 
                ${activityIdColumn} as activityId
              FROM activity_participants
              WHERE ${userIdColumn} IS NOT NULL AND ${activityIdColumn} IS NOT NULL
            `);
            console.log('已复制基本数据到临时表');
          } catch (innerError) {
            console.log('复制基本数据也失败:', innerError.message);
          }
        }
      }
      
      // 删除原表
      await queryRunner.dropTable('activity_participants');
      console.log('已删除原表');
      
      // 重命名临时表为正式表
      await queryRunner.query(`
        RENAME TABLE activity_participants_temp TO activity_participants
      `);
      console.log('已将临时表重命名为正式表');
      
      // 添加外键约束
      try {
        await queryRunner.query(`
          ALTER TABLE activity_participants
          ADD CONSTRAINT FK_activity_participants_user
          FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
        `);
        
        await queryRunner.query(`
          ALTER TABLE activity_participants
          ADD CONSTRAINT FK_activity_participants_activity
          FOREIGN KEY (activityId) REFERENCES activities(id) ON DELETE CASCADE
        `);
        console.log('已添加外键约束');
      } catch (error) {
        console.log('添加外键约束失败，可能是参考表不存在:', error.message);
      }
    } else {
      // 如果表不存在，直接创建新表
      console.log('activity_participants 表不存在，创建新表');
      
      await queryRunner.query(`
        CREATE TABLE activity_participants (
          id INT AUTO_INCREMENT PRIMARY KEY,
          userId INT NOT NULL,
          activityId INT NOT NULL,
          hasCheckedIn BOOLEAN DEFAULT false,
          checkinTime DATETIME NULL,
          joinTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      
      // 添加外键约束
      try {
        await queryRunner.query(`
          ALTER TABLE activity_participants
          ADD CONSTRAINT FK_activity_participants_user
          FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
        `);
        
        await queryRunner.query(`
          ALTER TABLE activity_participants
          ADD CONSTRAINT FK_activity_participants_activity
          FOREIGN KEY (activityId) REFERENCES activities(id) ON DELETE CASCADE
        `);
      } catch (error) {
        console.log('添加外键约束失败，可能是参考表不存在:', error.message);
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 不执行任何回滚操作
    console.log('此迁移不支持回滚操作');
  }
}


